﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';
    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限
            schedulePermission: true, // 能进到本页面，就是true
            scheduleCreatePermission: false,
            scheduleEditPermission: false,
            scheduleDeletePermission: false,
            scheduleDisablePermission: false,

            timeIntervalPermission: false,
            planPoolsPermission:false,

            multiDepartmentPermission: false,

            // 主页面
            filterName: '',
            dialogVisible: false, // 创建用户对话框，是否显示
            dialogTitle: '新建排班计划',
            actionType: '新建排班计划',
            tableData: [],
            treeData:[],
            formLabelWidth: '80px',
            department: null,   // 当前科室
            deviceType: null,    // 当前设备类型
            selectedRow: null,   // 当前选中行

            // 当前排班计划表
            schedule: {
                id: null,
                name: null,
                code: null,
                deviceTypeId: null,
                departmentId:null,
                order: 0,
                isActive: true,
                desc:null
            },

            defaultProps: {     // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 验证规则
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ]
            }
        },
        computed: {
            
        },
        watch: {
            
        },
        methods: {

            search() {
                var vm = this;
                if (!vm.filterName) {
                    vm.loadScheduleList();
                }
            },

            // 科室选中用户改变
            currentRowChange(val) {
                var vm = this;
                vm.selectedRow = val;
            },

            // 加载表格数据(只在初始化时执行一次)
            loadTableData() {
                var vm = this;
                return new Promise(resolve => {
                    if (vm.multiDepartmentPermission && vm.treeData[0].children.length > 0) { // admin 角色下，有科室
                        vm.department = vm.treeData[0].children[0]; // 默认加载tree中的第一个科室的用户情况
                        vm.loadScheduleList();
                    }
                    else if (vm.multiDepartmentPermission && vm.treeData[0].children.length === 0) { // admin角色下，系统中还没创建任何科室
                        // 提示系统还没有任何科室
                    }
                    else if (!vm.multiDepartmentPermission) { // 必然时是科室用户，而且必然是已经登录了某个科室，而且已经加载了科室
                        // 根据登录科室加载
                        vm.loadScheduleList();
                    }
                    resolve();
                })

            },

            // 加载科室设备类型下排班表
            loadScheduleList() {
                var vm = this;
                abp.ajax({
                    type: 'GET',
                    url: `/api/schedule/get-list?depId=${vm.department.id}&deviceTypeId=${vm.deviceType.id}&filterName=${vm.filterName}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.tableData = [...res.data];
                    }
                });
            },


            // 显示新建检查项目对话框
            showCreate() {
                var vm = this;
                vm.dialogTitle = '创建排班计划';
                vm.actionType = '创建';
                vm.schedule.order = 0;
                vm.schedule.isActive = true;
                vm.dialogVisible = true;
            },
           
            // 新建提交
            submitCreate() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/schedule/submit-create?depId=${vm.department.id}&deviceTypeId=${vm.deviceType.id}`,
                            data: JSON.stringify(vm.schedule)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.resetForm();
                                vm.loadScheduleList();
                            }
                        });
                    }
                });
            },

            // 打开编辑窗口
            showEdit(id) {
                var vm = this;
                vm.dialogTitle = '编辑排班计划';
                vm.actionType = '编辑';
                vm.loadDetail(id).then(() => {
                    vm.dialogVisible = true;
                })
            },

            // 编辑提交
            submitEdit() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/schedule/submit-edit?depId=${vm.department.id}&deviceTypeId=${vm.deviceType.id}`,
                            data: JSON.stringify(vm.schedule)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.loadScheduleList();
                                vm.resetForm();
                            }
                        })
                    }
                });
            },

            save() {
                var vm = this;
                if (vm.actionType.includes('编辑')) {
                    vm.submitEdit();
                }
                else {
                    vm.submitCreate();
                }
            },

            // 加载检查项目详情
            loadDetail(id) {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/schedule/get?id=${id}`
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.schedule = res.data;
                            resolve(res.data);
                        }
                    })
                });
            },

            // 加载科室（如果是科室用户时）
            loadDepartment() {
                return new Promise(resolve => {
                    if (!vm.multiDepartmentPermission) {
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }
                    else {
                        resolve();
                    }
                });
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                var vm = this;
                return new Promise(resolve => {
                    var url;
                    if (vm.multiDepartmentPermission) { // 如果有管理员角色（multiDepartmentPermission只在admin角色中才有）
                        url = `/api/exam-item/get-tree-data?depId=${null}`
                    }
                    else {
                        url = `/api/exam-item/get-tree-data?depId=${vm.department.id}`;
                    };
                    abp.ajax({
                        type: "GET",
                        url: url 
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.treeData = res.data;
                            if (vm.treeData[0].children.length > 0) { // 有科室存在
                                res.data[0].children.forEach((department, index) => {
                                    if (!vm.deviceType && department && department.children && department.children.length > 0) {
                                        vm.deviceType = vm.treeData[0].children[index].children[0];
                                        vm.department = department;
                                    }
                                })
                            }
                            else {
                                vm.tableShow = false;
                            }
                            resolve();
                        }
                    });
                });
            },

            // 加载当前权限
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('AppointManagerGroup.Schedule')) { // 检查项目管理权限
                        vm.schedulePermission = true;
                        if (abp.auth.isGranted('AppointManagerGroup.Schedule.Create')) {// 新建检查项目权限
                            vm.scheduleCreatePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.Schedule.Edit')) { // 编辑检查项目权限
                            vm.scheduleEditPermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.Schedule.Delete')) { // 删除检查项目权限
                            vm.scheduleDeletePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.Schedule.Disable')) { // 同步数据权限
                            vm.scheduleDisablePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.TimeInterval')) {
                            vm.timeIntervalPermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.PlanPool')) {
                            vm.planPoolsPermission = true;
                        }
                    }
                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) { // 多科室检查项目管理权限
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 查看排班计划的预约时段
            viewTimeInterval() {
                var vm = this;
                if (!vm.selectedRow) {
                    abp.message.warn("请选中排班计划！");
                }
                else {
                    window.open(`/Appointments/TimeIntervals?sid=${vm.selectedRow.id}`)
                }
            },

            // 查看号池计划
            viewPlanPool() {
                var vm = this;
                if (!vm.selectedRow) {
                    abp.message.warn("请选中排班计划！");
                }
                else {
                    window.open(`/Appointments/PlanPools?sid=${vm.selectedRow.id}`)
                }
            },

            disableToggle(id) {
                var vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/schedule/toggle-disable?id=${id}`
                }).then((res) => {
                    if (res.code === 0) {
                        abp.notify.success(res.msg);
                        vm.loadScheduleList();
                    }
                })
            },

            deleteSchedule(id) {
                var vm = this;
                abp.message.confirm("删除排班计划会造成系统异常")
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/schedule/delete?id=${id}`
                            }).then(res => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadScheduleList();
                                }
                            })
                        }
                    })
            },

            // 点击树节点
            nodeClicked(node, obj, aa) {
                if (node.icon != 'fa fa-hospital' && node.icon != 'fa fa-building') {
                    var vm = this;
                    vm.deviceType = node;
                    vm.department = obj.parent.data;
                    vm.loadScheduleList();
                }
            },

            // 表单重置
            resetForm() {
                var vm = this;
                vm.$refs['dialogForm'].resetFields();
                vm.dialogVisible = false;
                Object.keys(vm.schedule).forEach(key => {
                    vm.schedule[key] = null;
                });
            },

            // 初始化
            init() {
                var vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadDepartment().then(() => {
                            vm.loadTreeData().then(() => {
                                if (vm.department) {
                                    if (vm.deviceType) {
                                        vm.loadTableData().then(() => {
                                        });
                                    } else {
                                        abp.message.error('请配置科室设备类型！')
                                    }
                                } else {
                                    abp.message.error('请配置科室！');
                                }
                            });
                        })
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
        },
        mounted() {
        }
    });
});